import 'package:flutter/material.dart';

class LYDashLine extends StatefulWidget {
  final double? width;
  final double? height;
  final double lineHeight;
  final double dashSize;
  final double dashSpace;
  final Axis axis;
  final Color lineColor;

  const LYDashLine(
      {super.key,
      this.width = double.infinity,
      this.height = double.infinity,
      this.axis = Axis.horizontal,
      this.lineHeight = 1,
      this.dashSize = 5,
      this.dashSpace = 5,
      this.lineColor = Colors.white});

  @override
  State<LYDashLine> createState() => _LYDashLineState();
}

class _LYDashLineState extends State<LYDashLine> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.width,
      height: widget.height,
      child: CustomPaint(
        painter: DashLinePainter(
            axis: widget.axis,
            lineHeight: widget.lineHeight,
            dashSize: widget.dashSize,
            dashSpace: widget.dashSpace,
            lineColor: widget.lineColor),
      ),
    );
  }
}

class DashLinePainter extends CustomPainter {
  final Axis axis;
  final double lineHeight;
  final double dashSize;
  final double dashSpace;
  final Color lineColor;
  DashLinePainter(
      {required this.axis,
      this.lineHeight = 1,
      required this.dashSize,
      required this.dashSpace,
      required this.lineColor});
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint() // 创建一个画笔并配置其属性
      ..strokeWidth = lineHeight // 画笔的宽度
      ..isAntiAlias = true // 是否抗锯齿
      ..color = lineColor; // 画笔颜色

    var max = axis == Axis.horizontal ? size.width : size.height; // size获取到宽度
    final space = (dashSpace + dashSize);
    if (axis == Axis.horizontal) {
      double startX = 0;
      final y = size.height * 0.5;
      while (startX < max) {
        canvas.drawLine(Offset(startX, y), Offset(startX + dashSize, y), paint);
        startX += space;
      }
    } else {
      double startY = 0;
      final x = size.width * 0.5;
      while (startY < max) {
        canvas.drawLine(Offset(x, startY), Offset(x, startY + dashSize), paint);
        startY += space;
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
